<?php

namespace app\worker\library;

use think\App;
use Workerman\Worker;
use Workerman\Protocols\Http\Request;
use Workerman\Connection\TcpConnection;

/**
 * WorkerMan HTTP APP基础类
 * @property Worker        $worker
 * @property Request       $woRequest
 * @property TcpConnection $connection
 */
class WorkerHttpApp extends App
{
    /**
     * worker APP 初始化
     */
    public function init(TcpConnection $connection, Request $request): void
    {
        $this->beginTime  = microtime(true);
        $this->beginMem   = memory_get_usage();
        $this->woRequest  = $request;
        $this->connection = $connection;
        $this->setRuntimePath(root_path() . 'runtime' . DIRECTORY_SEPARATOR);

        $scriptFilePath = public_path() . 'index.php';
        $_SERVER        = array_merge($_SERVER, [
            'QUERY_STRING'         => $request->queryString(),
            'REQUEST_METHOD'       => $request->method(),
            'REQUEST_URI'          => $request->uri(),
            'SERVER_NAME'          => $request->host(true),
            'HTTP_HOST'            => $request->host(),
            'HTTP_USER_AGENT'      => $request->header('user-agent'),
            'HTTP_ACCEPT'          => $request->header('accept'),
            'HTTP_ACCEPT_LANGUAGE' => $request->header('accept-language'),
            'HTTP_ACCEPT_ENCODING' => $request->header('accept-encoding'),
            'HTTP_COOKIE'          => $request->header('cookie'),
            'HTTP_CONNECTION'      => $request->header('connection'),
            'CONTENT_TYPE'         => $request->header('content-type'),
            'HTTP_ORIGIN'          => $request->header('origin'),
            'HTTP_REFERER'         => $request->header('referer'),
            'HTTP_BATOKEN'         => $request->header('batoken'),
            'HTTP_BA_USER_TOKEN'   => $request->header('ba-user-token'),
            'SERVER_PROTOCOL'      => 'HTTP/' . $request->protocolVersion(),
            'SERVER_ADDR'          => $connection->getLocalIp(),
            'SERVER_PORT'          => $connection->getLocalPort(),
            'REMOTE_ADDR'          => $connection->getRemoteIp(),
            'REMOTE_PORT'          => $connection->getRemotePort(),
            'SCRIPT_FILENAME'      => $scriptFilePath,
            'SCRIPT_NAME'          => DIRECTORY_SEPARATOR . pathinfo($scriptFilePath, PATHINFO_BASENAME),
            'DOCUMENT_ROOT'        => dirname($scriptFilePath),
            'PATH_INFO'            => $request->path(),
        ]);

        $_GET     = $request->get();
        $_POST    = $request->post();
        $_FILES   = $request->file();
        $_REQUEST = array_merge($_REQUEST, $_GET, $_POST);

        $this->delete('lang');
        $this->delete('http');
        $this->delete('request');
        $this->delete('middleware');
    }
}